import { useCallback } from 'react';
import { message, notification } from 'antd';
import { AUTH_STORE, CART_STORE } from '@/constants';
import {
  resAddCart,
  resCartCheck,
  resCartList,
  resChangeCartNum,
  resDeleteCart,
} from '@/services/cart';
import { atom, AtomEffect, selector, useSetRecoilState } from 'recoil';
import { isValidTokenTime } from '@/utils/auth';
import { local } from '@/utils/storage';
import {formatCarts} from "@/utils/format";

export let resetCartStore: () => void;

const subscriptCartStore: AtomEffect<API.CartStruct[]> = ({
  resetSelf,
  setSelf,
  trigger,
}) => {
  const initSelf = async () => {
    const carts = await resCartList();
    if (carts) {
      setSelf(carts);
    }
  };

  const auth = local.get<AuthStructure>(AUTH_STORE, { token: '', expire: '' });
  if (auth.token && isValidTokenTime(auth.expire)) {
    initSelf();
  }

  resetCartStore = () => {
    resetSelf();
  };
};

export const cartStore = atom<API.CartStruct[]>({
  key: CART_STORE,
  default: [],
  effects_UNSTABLE: [subscriptCartStore],
});

export const cartShowState = selector({
  key: 'cartShowState',
  get: ({ get }) => {
    const carts = get(cartStore);
    return formatCarts(carts);
  },
});

export const cartCheckedState = selector({
  key: 'cartCheckedState',
  get: ({ get }) => {
    const carts = get(cartStore);
    let checkNum = 0;
    carts.forEach((cart) => {
      return cart.is_checked && checkNum++;
    });
    return checkNum;
  },
});

export const cartSumState = selector({
  key: 'cartSumState',
  get: ({ get }) => {
    const carts = get(cartStore);
    let cartSum = 0;
    carts.forEach((cart) => {
      if (cart.is_checked)
        cartSum += cart.goods?.price! * cart.goods?.discount! * cart.num;
    });
    return cartSum;
  },
});

export const useCartStore = () => {
  const setCartStore = useSetRecoilState(cartStore);

  const loadCart = useCallback(() => {
    resCartList().then((carts) => {
      setCartStore(carts);
    });
  }, []);

  const addCart = useCallback((data: API.AddCartParams) => {
    return resAddCart(data).then(() => {
      loadCart();
    });
  }, []);
  const deleteCart = useCallback((data: API.CartParams) => {
    resDeleteCart(data).then(() => {
      message.success('删除购物车成功');
      setCartStore((preState) => {
        return preState.filter((value) => {
          return !data.cart_ids.includes(value.id);
        });
      });
    });
  }, []);
  const checkCart = useCallback((data: API.CartParams) => {
    resCartCheck(data).then(() => {
      loadCart();
    });
  }, []);
  const changeCartNum = useCallback(
    (id: number, data: API.ChangeCartParams) => {
      resChangeCartNum(id, data).then(() => {
        loadCart();
      });
    },
    []
  );

  return {
    loadCart,
    addCart,
    deleteCart,
    checkCart,
    changeCartNum,
  };
};
